package com.itany.utils;

import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyHttpClientUtils {

    /**
     * http get请求方法
     * @param url
     * @return
     */
    public static String doGet(String url){
       //===============================代理设置===============================
       /* HttpHost httpHost = new HttpHost("223.82.106.253",	3128,"http");
        RequestConfig config = RequestConfig.custom()
                              .setProxy(httpHost)
                              .setConnectTimeout(100000)
                              .setSocketTimeout(100000)
                              .setConnectionRequestTimeout(100000)
                              .build();*/
        //===============================代理设置===============================
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        CloseableHttpResponse response =null;
        try {
            HttpGet httpGet = new HttpGet(url);
            //传入代理设置
            //httpGet.setConfig(config);
            //执行请求
            response = httpClient.execute(httpGet);
            //判断返回类型
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                result = EntityUtils.toString(response.getEntity(),Charset.defaultCharset());
            }else {
                result = response.getStatusLine().getStatusCode()+"";
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        return result;
    }


    /**
     * http post请求方法
     * @return
     */
    public static String doPost(String url, Map<String,String> params){
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //声明返回数据
        String result = "";
        //声明http响应对象
        CloseableHttpResponse response =null;
        try {
            //构建请求对象
            HttpPost post = new HttpPost(url);
            //构建参数
            if(params!=null){
                List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
                for(Map.Entry<String,String> param:params.entrySet()){
                    paramsList.add(new BasicNameValuePair(param.getKey(),param.getValue()));
                }
                //声明一个form对象
                UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(paramsList, Charset.defaultCharset());
                post.setEntity(encodedFormEntity);
            }
            //执行请求
            response = httpClient.execute(post);
            //判断返回类型
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                result = EntityUtils.toString(response.getEntity(),Charset.defaultCharset());
            }else {
                result = response.getStatusLine().getStatusCode()+"";
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            close(httpClient,response);
        }
         return result;
    }

    /**
     * 关闭链接方法
     */
    private static void close(CloseableHttpClient httpClient,CloseableHttpResponse response){

        try {
              if(response!=null){
                  response.close();
              }
              if(httpClient!=null){
                 httpClient.close();
              }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

//    public static void main(String[] args) {
//        //获取页面html信息
//        String html = MyHttpClientUtils.doGet("http://www.bookschina.com/");
//        //将其解析称呼为dom对象
//        Document document = Jsoup.parse(html,"UTF-8");
//        //通过class选择器选择相应节点
//        Elements p = document.getElementsByClass("c-category-list");
//        for(int i=0;i<p.size();i++){
//            Element element = p.get(i);
//            //获取二级A标签集合
//            Elements a = element.getElementsByTag("a");
//            for (int j=0;j<a.size();j++){
//                Element aelement=a.get(j);
//                System.out.println(aelement.text()+"==="+aelement.attr("href"));
//            }
//        }
//    }



}
